package com.hx.vending.service.impl;

import com.hx.vending.bean.*;
import com.hx.vending.bean.entity.EquipmentTypeCaseResult;
import com.hx.vending.bean.entity.RiseVO;
import com.hx.vending.bean.entity.TrailsReplenishment;
import com.hx.vending.bean.entity.TrailsVO;
import com.hx.vending.dao.*;
import com.hx.vending.mqtt.RunnerSendMqtt;
import com.hx.vending.service.ITrailsService;
import com.hx.vending.util.Msg;
import com.hx.vending.util.ToolUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2018/11/26.
 * 货道
 */
@Service
public class TrailsServiceImpl implements ITrailsService {

    @Autowired
    private TrailsMapper trailsMapper;

    @Autowired
    private ModelTrailsMapper modelTrailsMapper;

    @Autowired
    private EquipmentMapper equipmentMapper;

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private RiseMapper riseMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private EquipmentTypeCaseMapper equipmentTypeCaseMapper;

    @Autowired
    private EquipmentTypeRiseMapper equipmentTypeRiseMapper;

    /**
     * 添加货道信息
     * @param trails
     * @return
     */
    public Msg insertTrails(Trails trails, Integer modelId){
        if(ToolUtil.isNotEmpty(trails)){
            //添加货道信息
            int resultinsert = this.trailsMapper.insertSelective(trails);
            if(resultinsert != 0){
                //查询刚插入的货道信息，获取货道id
                trails = this.trailsMapper.selectByPrimaryKeySelective(trails);
                //如果设备id是空的，说明是添加的模板的货道，如果不是空的，就是直接给设备添加货道
                if(ToolUtil.isEmpty(trails.getTrailsEquipmentId()) && ToolUtil.isNotEmpty(modelId)){
                    //模板添加货道，需要添加模板关联信息
                    ModelTrails modelTrails = new ModelTrails();
                    modelTrails.setModelTrailsModelId(modelId);
                    modelTrails.setModelTrailsTrailsId(trails.getTrailsId());
                    modelTrails.setModelTrailsGoodsId(trails.getTrailsGoodsId());
                    modelTrails.setModelTrailsRiseId(trails.getTrailsRiseId());
                    int resultMT = this.modelTrailsMapper.insertSelective(modelTrails);
                    if(resultMT != 0){
                        return Msg.success();
                    }else{
                        return Msg.fail().add("msg", "未添加模板关联信息");
                    }
                }
                return Msg.fail().add("msg", "未添加模板关联信息");
            }else{
                return Msg.fail();
            }
        }else{
            return Msg.fail();
        }
    }


    /**
     * 修改货道信息
     * @param trails
     * @return
     */
    public Msg updateTrails(Trails trails, Integer modelId){
        if(ToolUtil.isNotEmpty(trails)){
            //修改货道信息
            int resultupdate = this.trailsMapper.updateByPrimaryKeySelective(trails);
            Trails newTrails = new Trails();
            newTrails.setTrailsId(trails.getTrailsId());
            Trails selectTrails = this.trailsMapper.selectByPrimaryKeySelective(newTrails);
            if(resultupdate != 0){
                //如果模板id不为空，修改模板关联表的信息,并且发送mqtt消息刷新商品

                //发送mqtt
                if (ToolUtil.isNotEmpty(selectTrails)) {
                    if (ToolUtil.isNotEmpty(selectTrails.getTrailsEquipmentId())) {
                        //设别id不为空，直接发送mqtt更新设备的商品信息
                        String fourNumber = ToolUtil.generateNonceStr(4);//随机数
                        RunnerSendMqtt runnerSendMqtt = new RunnerSendMqtt();
                        runnerSendMqtt.setMessage(selectTrails.getTrailsEquipmentId() + "," + fourNumber);
                        runnerSendMqtt.setRedisTemplate(redisTemplate);
                        runnerSendMqtt.setTheme("RefreshGoods");
                        runnerSendMqtt.setThreadName("刷新货道库存指令");
                        runnerSendMqtt.setRedisKey("RefreshGoods-" + selectTrails.getTrailsEquipmentId());
                        runnerSendMqtt.start();
                    }else {
                        //查出模板信息，应用该模板的设备全部更新
                        Rise rise = new Rise();
                        rise.setRiseId(selectTrails.getTrailsRiseId());
                        Rise selectRise = this.riseMapper.selectByPrimaryKeySelective(rise);
                        if (ToolUtil.isNotEmpty(selectRise)) {
                            //查询应用该模板的设备
                            Equipment equipment = new Equipment();
                            equipment.setEquipmentModelId(selectRise.getRiseModelId());
                            List<Equipment> equipmentList = this.equipmentMapper.selectByExample(equipment);
                            if (ToolUtil.isNotEmpty(equipmentList)) {
                                for (Equipment forEquipment: equipmentList) {
                                    String fourNumber = ToolUtil.generateNonceStr(4);//随机数
                                    RunnerSendMqtt runnerSendMqtt = new RunnerSendMqtt();
                                    runnerSendMqtt.setMessage(forEquipment.getEquipmentId() + "," + fourNumber);
                                    runnerSendMqtt.setRedisTemplate(redisTemplate);
                                    runnerSendMqtt.setTheme("RefreshGoods");
                                    runnerSendMqtt.setThreadName("刷新货道库存指令");
                                    runnerSendMqtt.setRedisKey("RefreshGoods-" + forEquipment.getEquipmentId());
                                    runnerSendMqtt.start();
                                }
                            }
                        }
                    }
                }

                //查出当前货到的模板关联信息
                ModelTrails modelTrails = new ModelTrails();
                modelTrails.setModelTrailsTrailsId(trails.getTrailsId());
                ModelTrails resultModelTrails = modelTrailsMapper.selectByPrimaryKeySelective(modelTrails);
                if(null != resultModelTrails){
                    //如果商品id有变化，需要更改关联表里的商品信息
                    if(ToolUtil.isEmpty(resultModelTrails.getModelTrailsGoodsId()) || resultModelTrails.getModelTrailsGoodsId() != trails.getTrailsGoodsId()){
                        modelTrails = new ModelTrails();
                        modelTrails.setModelTrailsId(resultModelTrails.getModelTrailsId());
                        modelTrails.setModelTrailsGoodsId(trails.getTrailsGoodsId());
                        modelTrailsMapper.updateByPrimaryKeySelective(modelTrails);
                    }
                }else{
                    return Msg.fail().add("msg", "未找到模板关联信息");
                }
                return Msg.success();
            }else{
                return Msg.fail();
            }
        }else{
            return Msg.fail();
        }
    }


    /**
     * 删除货道信息
     * @param trailsId 货道id
     * @return Msg
     */
    public Msg deleteTrails(Integer trailsId){
        if (ToolUtil.isNotEmpty(trailsId)){
            int resultdelete = this.trailsMapper.deleteByPrimaryKey(trailsId);
            if (resultdelete != 0){
                //查询模板关联表
                ModelTrails modelTrails = new ModelTrails();
                modelTrails.setModelTrailsTrailsId(trailsId);
                ModelTrails resultModelTrails = this.modelTrailsMapper.selectByPrimaryKeySelective(modelTrails);
                if (ToolUtil.isNotEmpty(resultModelTrails)){
                    //如果当前货道在模板关联中存在，就删除
                    this.modelTrailsMapper.deleteByPrimaryKey(resultModelTrails.getModelTrailsId());
                }
            }
            return Msg.success();
        }else{
            return Msg.fail().add("msg", "货道id不能为空");
        }
    }


    /**
     * 根据货道id查询补货时所需信息
     * @param trailsId
     * @return
     */
    public Msg selectReplenishmentMessage(Integer trailsId){

        if (ToolUtil.isNotEmpty(trailsId)) {
            //查询货道信息
            Trails trails = new Trails();
            trails.setTrailsId(trailsId);
            Trails selectTrails = this.trailsMapper.selectByPrimaryKeySelective(trails);
            if (ToolUtil.isNotEmpty(selectTrails)) {

                Equipment selectEquipment = null;
                Goods selectGoods = null;
                TrailsReplenishment trailsReplenishment = new TrailsReplenishment();

                //查询设备信息
                if (ToolUtil.isNotEmpty(selectTrails.getTrailsEquipmentId())) {
                    Equipment equipment = new Equipment();
                    equipment.setEquipmentId(selectTrails.getTrailsEquipmentId());
                    selectEquipment = this.equipmentMapper.selectByPrimary(equipment);

                    trailsReplenishment.setEquipmentId(selectEquipment.getEquipmentId());
                    trailsReplenishment.setEquipmentNumber(selectEquipment.getEquipmentNumber());
                }
                //查询商品信息
                if (ToolUtil.isNotEmpty(selectTrails.getTrailsGoodsId())) {
                    Goods goods = new Goods();
                    goods.setGoodsId(selectTrails.getTrailsGoodsId());
                    selectGoods = this.goodsMapper.selectByPrimaryKeySelective(goods);

                    trailsReplenishment.setGoodsName(selectGoods.getGoodsName());
                    trailsReplenishment.setGoodsPicture(selectGoods.getGoodsPicture());
                    trailsReplenishment.setGoodsPrice(selectGoods.getGoodsPrice());
                    trailsReplenishment.setGoodsRemark(selectGoods.getGoodsRemark());
                    trailsReplenishment.setGoodsId(selectTrails.getTrailsGoodsId());
                }

                trailsReplenishment.setRiseNumber(selectTrails.getTrailsRiseId().toString());
                trailsReplenishment.setTrailsGoodsCapacity(selectTrails.getTrailsGoodsCapacity());
                trailsReplenishment.setTrailsGoodsStock(selectTrails.getTrailsGoodsStock());
                trailsReplenishment.setTrailsNumber(selectTrails.getTrailsNumber());
                trailsReplenishment.setTrailsType(selectTrails.getTrailsType());
                trailsReplenishment.setTrailsTrackTime(selectTrails.getTrailsTrackTime());

                return Msg.success().add("message", trailsReplenishment);
            }else {
                return Msg.fail();
            }
        }else {
            return Msg.fail();
        }
    }

    /**
     * 货道补货（单个）
     * @param goodsId
     * @param trailsId
     * @param goodsNumber
     * @return
     */
    public Msg updateReplenishmentMessage(String goodsId, Integer trailsId, Integer goodsNumber){
        if (ToolUtil.isNotEmpty(trailsId) && ToolUtil.isNotEmpty(goodsId) && "null" != goodsId) {
            Integer id=0;
            try {
                id = Integer.parseInt(goodsId);
            }catch (Exception e) {
                return Msg.fail().add("msg", "请输入正确商品信息");
            }
            //查询货道信息
            Trails trails = new Trails();
            trails.setTrailsId(trailsId);
            Trails selectTrails = this.trailsMapper.selectByPrimaryKeySelective(trails);
            if (ToolUtil.isNotEmpty(selectTrails)) {
                //修改库存数量
                Integer stock = 0;
                if (id != selectTrails.getTrailsGoodsId()) {
                    //更换了商品
                    stock = goodsNumber;
                    trails.setTrailsGoodsId(id);
                }else {
                    //未更换商品
                    stock = goodsNumber;
                }
                if (stock > selectTrails.getTrailsGoodsCapacity()) {
                    return Msg.fail().add("msg", "超出库存容量");
                }
                trails.setTrailsGoodsStock(stock);
                this.trailsMapper.updateByPrimaryKeySelective(trails);

                if (ToolUtil.isNotEmpty(selectTrails.getTrailsEquipmentId())) {
                    String fourNumber = ToolUtil.generateNonceStr(4);//随机数
                    //有设备id
                    //发送MQTT消息
                    RunnerSendMqtt runnerSendMqtt = new RunnerSendMqtt();
                    runnerSendMqtt.setMessage(selectTrails.getTrailsEquipmentId() + "," + fourNumber);
                    runnerSendMqtt.setRedisTemplate(redisTemplate);
                    runnerSendMqtt.setTheme("RefreshGoods");
                    runnerSendMqtt.setThreadName("刷新货道库存指令");
                    runnerSendMqtt.setRedisKey("RefreshGoods-" + selectTrails.getTrailsEquipmentId());
                    runnerSendMqtt.start();
                }
            }
            return Msg.success();
        }else {
            return Msg.fail().add("msg", "商品、货道信息为空");
        }
    }


    /**
     * 设备一键补货
     * @param equipmentId
     * @return
     */
    public Msg updateupdateAllReplenishmentMessage(String equipmentId) {

        if (ToolUtil.isNotEmpty(equipmentId)) {

            //查询设备的货道信息
            Trails trails = new Trails();
            trails.setTrailsEquipmentId(equipmentId);
            List<Trails> trailsList = this.trailsMapper.selectByExampleSelective(trails);
            if (ToolUtil.isNotEmpty(trailsList)) {
                for (Trails forTrails: trailsList) {
                    if (forTrails.getTrailsGoodsStock() != forTrails.getTrailsGoodsCapacity() && ToolUtil.isNotEmpty(forTrails.getTrailsGoodsId())) {
                        //库存不是满的将库存补满,并且货道里要有商品
                        forTrails.setTrailsGoodsStock(forTrails.getTrailsGoodsCapacity());
                        this.trailsMapper.updateByPrimaryKeySelective(forTrails);
                    }
                }

                //发送mqtt消息
                String fourNumber = ToolUtil.generateNonceStr(4);//随机数
                RunnerSendMqtt runnerSendMqtt = new RunnerSendMqtt();
                runnerSendMqtt.setMessage(equipmentId + "," + fourNumber);
                runnerSendMqtt.setRedisTemplate(redisTemplate);
                runnerSendMqtt.setTheme("RefreshGoods");
                runnerSendMqtt.setThreadName("刷新货道库存指令");
                runnerSendMqtt.setRedisKey("RefreshGoods-" + equipmentId);
                runnerSendMqtt.start();
            }else {
                return Msg.fail().add("msg", "设备的货道信息不存在!!");
            }

            return Msg.success();
        }else {
            return Msg.fail().add("msg", "设备id为空!!");
        }
    }


    /**
     * 货道故障解决
     * @param trailsId
     * @return
     */
    public Msg updateTrailsFaultResolution(Integer trailsId) {

        if (ToolUtil.isNotEmpty(trailsId)) {

            Trails trails = new Trails();
            trails.setTrailsId(trailsId);
            Trails selectTrails = this.trailsMapper.selectByPrimaryKeySelective(trails);
            trails.setTrailsAlarm(0);//未故障
            int i = this.trailsMapper.updateByPrimaryKeySelective(trails);

            if (i != 0) {

                //发送mqtt消息
                String fourNumber = ToolUtil.generateNonceStr(4);//随机数
                RunnerSendMqtt runnerSendMqtt = new RunnerSendMqtt();
                runnerSendMqtt.setMessage(selectTrails.getTrailsEquipmentId() + "," + fourNumber);
                runnerSendMqtt.setRedisTemplate(redisTemplate);
                runnerSendMqtt.setTheme("RefreshGoods");
                runnerSendMqtt.setThreadName("刷新货道库存指令");
                runnerSendMqtt.setRedisKey("RefreshGoods-" + selectTrails.getTrailsEquipmentId());
                runnerSendMqtt.start();

                return Msg.success();
            }else {
                return Msg.fail();
            }
        }else {
            return Msg.fail().add("msg", "货道id为空!!");
        }
    }

    @Override
    public List<Trails> selectByExample(Trails trails) {
        return trailsMapper.selectByExample(trails);
    }

    @Override
    public int deleteByEquipmentId(String equipmentId) {
        return trailsMapper.deleteByEquipmentId(equipmentId);
    }

    @Override
    public Trails selectByPrimaryKeySelective(Trails trails) {
        return trailsMapper.selectByPrimaryKeySelective(trails);
    }

    @Override
    public int updateByPrimaryKey(Trails trails) {
        return trailsMapper.updateByPrimaryKeySelective(trails);
    }

    @Override
    public int updateByTrails(Trails trails) {
        return trailsMapper.updateByTrails(trails);
    }


    /**
     * 货道故障解决
     * @param equipmentId
     * @return
     */
    public Msg selectTrailsAlarm(String equipmentId) {

        if (ToolUtil.isNotEmpty(equipmentId)) {

            //保存箱柜信息
            List<EquipmentTypeCaseResult> caseList = new ArrayList<EquipmentTypeCaseResult>();

            //查询设备信息
            Equipment equipment = new Equipment();
            equipment.setEquipmentId(equipmentId);
            Equipment selectEquipment = this.equipmentMapper.selectByPrimary(equipment);

            if (ToolUtil.isNotEmpty(selectEquipment)) {

                //查询出该设备的机箱编号分组
                List<Trails> trailsCaseList = this.trailsMapper.selectCaseGroupBy(equipmentId);

                if (ToolUtil.isNotEmpty(trailsCaseList)) {
                    for (Trails caseNumber:trailsCaseList) {

                        //返回层信息的集合
                        List<Object> riseVOList = new ArrayList<Object>();

                        //查询该设备该机箱的层编号分组
                        List<Trails> trailsRiseList = this.trailsMapper.selectRiseGroupBy(caseNumber.getTrailsCaseId(), equipmentId);

                        if (ToolUtil.isNotEmpty(trailsRiseList)) {
                            for (Trails riseNumber:trailsRiseList) {

                                //返回货道信息的集合
                                List<TrailsVO> trailsVOS = new ArrayList<TrailsVO>();

                                //查询该设备该机箱该层的货道信息
                                Trails trails = new Trails();
                                trails.setTrailsEquipmentId(equipmentId);
                                trails.setTrailsCaseId(caseNumber.getTrailsCaseId());
                                trails.setTrailsRiseId(riseNumber.getTrailsRiseId());
                                List<Trails> trailss = this.trailsMapper.selectByExample(trails);
                                if (ToolUtil.isNotEmpty(trailss)) {
                                    for (Trails forTrails:trailss) {
                                        //保存货道信息
                                        TrailsVO trailsVO = new TrailsVO();
                                        trailsVO.setTrailsId(forTrails.getTrailsId());
                                        trailsVO.setTrailsNumber(forTrails.getTrailsNumber());
                                        trailsVO.setTrailsPosition(forTrails.getTrailsPosition());
                                        trailsVO.setTrailsAlarm(forTrails.getTrailsAlarm());

                                        trailsVOS.add(trailsVO);
                                    }
                                }
                                //保存层信息
                                RiseVO riseVO = new RiseVO();
                                riseVO.setRiseNumber(riseNumber.getTrailsRiseId().toString());
                                riseVO.setTrailsVOList(trailsVOS);

                                riseVOList.add(riseVO);
                            }
                        }
                        //保存机箱信息
                        EquipmentTypeCaseResult equipmentTypeCaseResult = new EquipmentTypeCaseResult();
                        equipmentTypeCaseResult.setCaseNumber(caseNumber.getTrailsCaseId());
                        equipmentTypeCaseResult.setCaseList(riseVOList);

                        caseList.add(equipmentTypeCaseResult);
                    }
                }
            }
            return Msg.success().add("riseVOList", caseList);
        }else {
            return Msg.fail().add("msg", "设备id为空!!");
        }
    }

}
